package com.ruoyi.common.utils;


import org.springframework.stereotype.Component;

import java.math.BigInteger;
public class SnowflakeIDGenerator {
    private final long workerId;
    private final long epoch = 1620000000000L; // 起始时间戳，自行设置，这里设置为2021-05-03 00:00:00
    private long sequence = 0L;
    private final long workerIdBits = 5L;
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final long timestampLeftShift = 22L;
    private final long sequenceMask = -1L ^ (-1L << 12L);
    private long lastTimestamp = -1L;

    public SnowflakeIDGenerator(long workerId) {
        if (workerId < 0 || workerId > maxWorkerId) {
            throw new IllegalArgumentException(String.format("Worker ID must be between 0 and %d", maxWorkerId));
        }
        this.workerId = workerId;
    }

    public synchronized String nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;
        return convertToStudentID(((timestamp - epoch) << timestampLeftShift) | (workerId << 12) | sequence);
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }


    public static String convertToStudentID(long snowflakeID) {
        // 将64位ID直接截取为10位数字
        String studentID = String.valueOf(snowflakeID);
        // 如果长度不足十位，则在前面补0
        if (studentID.length() < 10) {
            studentID = String.format("%010d", Long.parseLong(studentID));
        } else if (studentID.length() > 10) {
            // 如果长度超过十位，则截取后十位
            studentID = studentID.substring(studentID.length() - 10);
        }
        return studentID;
    }
}
